package com.github.ilioili.qqlogin;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.open.utils.HttpUtils;
import com.tencent.tauth.IRequestListener;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;

/**
 * Created by User on 16/6/14.
 */
public class QqLoginBridgeActivity extends Activity {
    public static final String APP_ID = "1105384945";
    public static final String SCOPE = "get_simple_userinfo";
    public Tencent mTencent;
    private SharedPreferences sharedPreferences;
    private static OnUserInfoListener onUserInfoListener;

    private IUiListener iUiListener = new IUiListener() {
        @Override
        public void onComplete(Object o) {
            try {
                JSONObject jsonObject = (JSONObject) o;
                String openid = jsonObject.getString("openid");
                String access_token = jsonObject.getString("access_token");
                String expires_in = jsonObject.get("expires_in") + "";
                mTencent.setAccessToken(access_token, expires_in);
                SharedPreferences.Editor edit = sharedPreferences.edit();
                edit.putString("access_token", access_token);
                edit.putString("openid", openid);
                edit.putString("expires_in", expires_in);
                edit.apply();
                mTencent.setOpenId(openid);
                getUserInfo();
                Log.e("QQ", o.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError uiError) {
            Log.e("QQ", "error");
        }

        @Override
        public void onCancel() {
            Log.e("QQ", "cancel");
        }
    };

    private void getUserInfo() {
        UserInfo info = new UserInfo(this, mTencent.getQQToken());
        info.getUserInfo(new IUiListener() {
            @Override
            public void onComplete(Object o) {
                try {
                    JSONObject jsonObject = (JSONObject) o;
                    String name = jsonObject.getString("nickname");
                    String icon = jsonObject.getString("figureurl_qq_2");
                    sharedPreferences.edit().putBoolean("isLogined", true).apply();
                    onUserInfoListener.onUserInfoObtained(name, icon, "QQ_" + mTencent.getOpenId());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(UiError uiError) {

            }

            @Override
            public void onCancel() {

            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(null==sharedPreferences) {
            sharedPreferences = getSharedPreferences("QQ", Context.MODE_PRIVATE);
            mTencent = Tencent.createInstance(APP_ID, getApplicationContext());
        }
//        if (sharedPreferences.getBoolean("isLogined", false)) {
//            mTencent.setAccessToken(sharedPreferences.getString("access_token", ""), sharedPreferences.getString("expires_in", ""));
//            mTencent.setOpenId(sharedPreferences.getString("openid", ""));
//            if (mTencent.isSessionValid()) {
//                getUserInfo();
//                finish();
//                return;
//            }
//        }
        Toast.makeText(this,"JustDoIt将打开QQ授权登陆", Toast.LENGTH_SHORT ).show();
        mTencent.login(this, SCOPE, iUiListener);
    }

    public static void login(Activity activity, OnUserInfoListener listener) {
        onUserInfoListener = listener;
        Intent intent = new Intent(activity, QqLoginBridgeActivity.class);
        activity.startActivity(intent);
        activity.overridePendingTransition(0, 0);
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK && requestCode == Constants.REQUEST_LOGIN) {
            Tencent.onActivityResultData(requestCode, resultCode, data, iUiListener);
        }
        finish();
    }

    public interface OnUserInfoListener {
        void onUserInfoObtained(String name, String iconUrl, String id);
    }

}
